// 复制
// v-copy="文字"
export const copy = {
    mounted(el, { value }) {
        el._value = value
        el.handler = () => {
            if (!el._value) {
                // 复制的值为空时，给出的提示操作。
                console.log('无可复制的内容')
                return
            }

            // 创建 textarea 标签
            const textarea = document.createElement('textarea')
            // 设置readOnly(规定字段为只读)属性，防止 iOS下自动唤起键盘，并移除可视区域
            textarea.readOnly = 'readOnly'
            textarea.style.position = 'absolute'
            textarea.style.left = '-9999px'
            // 将需要复制的值，赋给 textarea 标签的 value  值
            textarea.value = el._value 
            // 将 textarea 插入到 body 中
            document.body.appendChild(textarea)

            // 选中值并复制
            textarea.select()
            const result = document.execCommand('Copy')
            if (result) {
                console.log('复制成功')
            }
            document.body.removeChild(textarea)
        }
        // 绑定点击事件
        el.addEventListener('click', el.handler)
    },
    // 当传进来的值更新的时候触发
    updated(el, { value }) {
        el._value = value
    },
    // 指令与元素解绑的时候触发，移除事件绑定
    unmounted(el) {
        el.removeEventListener('click', el.handler)
    }
}
// 长按事件
// v-longpress:长按时间="方法"
// 默认2s
export const longpress = {
    mounted(el, binding, vNode) {
        // 没有绑定函数抛出错误
        if (typeof binding.value !== 'function') {
            throw 'longpress callback not a function'
        }

        // 计时器变量
        el._timer = null
        // 运行函数
        el._handler = e => {
            binding.value(e)
        }
        // 创建计时器（2秒后执行函数）
        el._start = e => {
            // 0为鼠标左键
            if (e.type === 'click' && e.button !== 0) return

            if (el._timer === null) {
                el._timer = setTimeout(_ => {
                    el._handler()
                }, binding.arg || 2000)

                // 取消浏览器默认事件
                el.addEventListener('contextmenu', e => {
                    e.preventDefault()
                })
            }
        }
        // 两秒内松手，取消计时器
        el._cancel = e => {
            if (el._timer !== null) {
                clearTimeout(el._timer)
                el._timer = null
            }
        }

        // 添加计时监听
        el.addEventListener('mousedown', el._start)
        el.addEventListener('touchstart', el._start)
        // 添加取消监听
        el.addEventListener('click', el._cancel)
        el.addEventListener('mouseout', el._cancel)
        el.addEventListener('touchend', el._cancel)
        el.addEventListener('touchcancel', el._cancel)
    },
    unmounted(el) {
        // 移除监听
        el.removeEventListener('mousedown', el._start)
        el.removeEventListener('touchstart', el._start)
        el.removeEventListener('click', el._cancel)
        el.removeEventListener('mouseout', el._cancel)
        el.removeEventListener('touchend', el._cancel)
        el.removeEventListener('touchcancel', el._cancel)
    }
}
// 防抖
// v-debounce:时间="方法"
// 事件默认 1s
export const debounce = {
    mounted: (el, binding) => {
        // 没有绑定函数抛出错误
        if (typeof binding.value !== 'function') {
            throw 'debounce callback not a function'
        }

        let timer
        el.addEventListener('click', () => {
            if (timer) clearTimeout(timer)

            timer = setTimeout(_ => {
                binding.value()
            }, binding.arg || 1000)
        })
    },
    unmounted: (el, binding) => {
        el.removeEventListener('click', el._handler)
    }
}
// 节流
// v-throttle:时间="方法"
// 事件默认 1s
export const throttle = {
    mounted: (el, binding) => {
        console.log('binding', binding.arg)
        // 没有绑定函数抛出错误
        if (typeof binding.value !== 'function') {
            throw 'throttle callback not a function'
        }

        // 开关
        el._flag = true
        el._timer = null
        el._handler = () => {
            if (!el._flag) return

            // 函数执行后关闭开关
            el._flag && binding.value()
            el._flag = false

            if (el._timer) clearTimeout(el._timer)

            el._timer = setTimeout(_ => {
                el._flag = true
            }, binding.arg || 1000)
        }
        el.addEventListener('click', el._handler)
    },
    unmounted: (el, binding) => {
        el.removeEventListener('click', el._handler)
    }
}
// 点击元素外指令
export const clickOut = {
    mounted: (el, binding) => {
        el._handler = e => {
            // 判断点击的元素是否本身，是则返回
            if (el.contains(e.target)) return

            // 如果绑定了函数，则调用函数
            if (typeof binding.value === 'function') {
                binding.value()
            }
        }

        // 添加事件监听
        setTimeout(_ => {
            document.addEventListener('click', el._handler)
        }, 0)
    },
    unmounted(el) {
        // 解除事件监听
        document.removeEventListener('click', el._handler)
    }
}
// 拖拽
export const draggable = {
    mounted: (el) => {
        el.style.cursor = 'move'
        el._onmousedown = e => {
            // 记录当前的left、top值
            let disX = e.pageX - el.offsetLeft
            let disY = e.pageY - el.offsetTop

            // 鼠标移动
            document.onmousemove = e => {
                let x = e.pageX - disX
                let y = e.pageY - disY

                // 临界值处理
                let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
                let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)

                if (x < 0) {
                    x = 0
                } else if (x > maxX) {
                    x = maxX
                }

                if (y < 0) {
                    y = 0
                } else if (y > maxY) {
                    y = maxY
                }

                el.style.left = `${x}px`
                el.style.top = `${y}px`
            }
            document.onmouseup = _ => {
                document.onmousemove = document.onmouseup = null
            }
        }
    }
}
// 数字输入指令
// 默认只能输入整数
// 保留位数 v-inputNumber.float="位数"
export const inputNumber = {
    mounted: (el, binding, vnode) => {
        console.log('binding',binding)
        // 定位输入框
        let input = el.tagName === 'INPUT' ? el : vnode.elm.children[0]
        // compositionstart -> 开始新的输入合成时会触发
        input.addEventListener('compositionstart', _ => {
            vnode.inputLocaking = true
        })
        // compostitonend -> 合成完成或取消时触发
        input.addEventListener('compostitonend', _ => {
            vnode.inputLocaking = false
            input.dispatchEvent(new Event('input'))
        })
        input.addEventListener('input', _ => {
            if (vnode.inputLocaking) return

            let oldValue = input.value
            let newValue = input.value

            if (binding.modifiers.float) {
                // 清除数字和‘.’以外的字符
                newValue = newValue.replace(/[^\d.]/g, '')
                // 只保留第一个‘.’，清除多余的
                newValue = newValue.replace(/\.{2,}/g, '.')
                // 第一个字符如果是‘.’，补充前缀0
                newValue = newValue.replace(/^\./g, '0.')
                // 0开头的只有保留第一个0，清除多余的
                newValue = newValue.replace(/^0{2,}/g, '0')
                // 两位数以上不能0开头
                if (/^0\d+/.test(newValue)) {
                    newValue = newValue.slice(1)
                }
                // 保证‘.’只出现一次，而不能出现两次以上
                newValue = newValue.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')

                // 保留几位小数
                if (typeof binding.value !== 'undefined') {
                    // 期望保留的最大小数位数
                    let pointKeep = 0
                    if (typeof binding.value === 'string' || typeof binding.value === 'number') {
                        pointKeep = parseInt(binding.value)
                    }
                    if (!isNaN(pointKeep)) {
                        if (!Number.isInteger(pointKeep) || pointKeep < 0) {
                            pointKeep = 0
                        }
                        const str = '^(\\d+)\\.(\\d{'+pointKeep+'}).*$'
                        const reg = new RegExp(str)
                        if (pointKeep === 0) {
                            // 不需要小数点
                            newValue = newValue.replace(reg, '$1')
                        } else {
                            // 通过正则表达式保留小数点后指定的位数
                            newValue = newValue.replace(reg, '$1.$2')
                        }
                    }
                }
            } else {
                // 只保留整数
                newValue = newValue.replace(/[^\d.]/g, '')
                newValue = newValue ? parseInt(newValue) : ''
            }

            // 判断是否需要更新，避免进入死循环
            if (+newValue !== +oldValue) {
                input.value = newValue
                input.dispatchEvent(new Event('input'))
            }
        })
    }
}
// 水印
export const waterMarker = {
    mounted: function (el, binding) {
        addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
    }
}
function addWaterMarker (str, parentNode, font, textColor) {
    // 水印文字，父元素，字体，文字颜色
    var can = document.createElement('canvas')
    parentNode.appendChild(can)
    can.width = 200
    can.height = 150
    can.style.display = 'none'
    var cans = can.getContext('2d')
    cans.rotate((-20 * Math.PI) / 180)
    cans.font = font || '16px Microsoft JhengHei'
    cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
    cans.textAlign = 'left'
    cans.textBaseline = 'Middle'
    cans.fillText(str, can.width / 10, can.height / 2)
    parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'
}


